package com.tuzhi.convert.mq;

import lombok.Data;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Data
public class RabbitmqConfig {
    @Value("${convertMq.queueName}")
    private String queueName;
    @Value("${convertMq.exchangeName}")
    private String exchangeName;
    @Value("${convertMq.routingKey}")
    private String routingKey;


    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Bean
    public Queue converterQueue() {
        /**
         * name: 队列名称
         * durable 是否持久化
         * exclusive 是否是排他队列 只有创建者可以使用
         * autoDelete 声明此队列为临时队列，最后一个消费者使用完自动删除
         */
        return new Queue(queueName, true, false, false);
    }

    @Bean
    public Binding converterBinding() {
        return BindingBuilder
                .bind(converterQueue())
                .to(msgExchange())
                .with(routingKey);
    }

    @Bean
    public TopicExchange msgExchange() {
        return new TopicExchange(queueName, true, false);
    }

    @Bean(name = "consListenerContainer_convert")
    public SimpleRabbitListenerContainerFactory mqConsumerlistenerContainer() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPrefetchCount(1);//每次只能获取一条消息，处理完成才能获取下一个消息
        return factory;
    }
}
